/*
 * Wazuh Vulnerability Scanner - Unit Tests
 * Copyright (C) 2015, Wazuh Inc.
 * March 5, 2024.
 *
 * This program is free software; you can redistribute it
 * and/or modify it under the terms of the GNU General Public
 * License (version 2) as published by the FSF - Free Software
 * Foundation.
 */

#include "scanOsAlertDetailsBuilder_test.hpp"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_deltas_generated.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_deltas_schema.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_synchronization_generated.h"
#include "../../../../shared_modules/utils/flatbuffers/include/syscollector_synchronization_schema.h"
#include "../scanOrchestrator/scanOsAlertDetailsBuilder.hpp"
#include "MockDatabaseFeedManager.hpp"
#include "MockOsDataCache.hpp"
#include "MockRemediationDataCache.hpp"
#include "TrampolineOsDataCache.hpp"
#include "TrampolineRemediationDataCache.hpp"
#include "flatbuffers/flatbuffer_builder.h"
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "json.hpp"
#include <unistd.h>

using ::testing::_;
using ::testing::HasSubstr;
using ::testing::ThrowsMessage;

namespace NSScanOsAlertDetailsBuilderTest
{
    constexpr auto TEST_DESCRIPTION_DATABASE_PATH {"queue/vd/descriptions"};

    const std::string OS_SCAN_MSG =
        R"({
                "agent_info": {
                    "agent_id": "002"
                },
                "data_type": "state",
                "data": {
                    "attributes_type": "syscollector_osinfo",
                    "attributes": {
                        "architecture": "x86_64",
                        "checksum": "1691178971959743855",
                        "hostname":"fd9b83c25f30",
                        "os_major":"10",
                        "os_minor":"0",
                        "os_build":"19045.4046",
                        "os_name":"Microsoft Windows 10 Pro",
                        "os_display_version":"22H2",
                        "os_platform":"windows",
                        "os_version":"10.0.19045.4043",
                        "scan_time":"2023/08/04 19:56:11"
                    }
                }
            })";

    const std::string CVEID {"CVE-2024-1234"};
} // namespace NSScanOsAlertDetailsBuilderTest

// Shared pointers definitions
std::shared_ptr<MockOsDataCache> spOsDataCacheMock;
std::shared_ptr<MockRemediationDataCache> spRemediationDataCacheMock;

using namespace NSScanOsAlertDetailsBuilderTest;

void ScanOsAlertDetailsBuilderTest::SetUp()
{
    std::filesystem::create_directories("queue/vd");

    // Policy manager initialization.
    const auto& configJson {nlohmann::json::parse(R"({
    "vulnerability-detection": {
        "enabled": "yes",
        "index-status": "yes",
        "cti-url": "cti-url.com"
    },
    "osdataLRUSize":1000,
    "clusterName":"cluster01",
    "clusterEnabled":false
    })")};
    PolicyManager::instance().initialize(configJson);
}

void ScanOsAlertDetailsBuilderTest::TearDown()
{
    spOsDataCacheMock.reset();
    spRemediationDataCacheMock.reset();
    PolicyManager::instance().teardown();
    std::filesystem::remove_all("queue/vd");
}

TEST_F(ScanOsAlertDetailsBuilderTest, TestSuccessfulScanOsAlertAffects)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, setOsData(_, _)).Times(1);
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    spRemediationDataCacheMock = std::make_shared<MockRemediationDataCache>();
    EXPECT_CALL(*spRemediationDataCacheMock, getRemediationData(_)).WillRepeatedly(testing::Return(Remediation {}));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_synchronization_SCHEMA));
    ASSERT_TRUE(parser.Parse(OS_SCAN_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorSynchronization::GetSyncMsg(reinterpret_cast<const char*>(buffer));
    auto scanContext =
        std::make_shared<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>(
            syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"INSERTED"})"_json;
    scanContext->m_isFirstScan = false;
    scanContext->m_matchConditions[CVEID] = {"version", MatchRuleCondition::Unknown};

    TScanOsAlertDetailsBuilder<MockDatabaseFeedManager,
                               TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>
        scanOsAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(scanOsAlertDetailsAugmentation.handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);
    EXPECT_NE(scanContext->m_elements.find(CVEID), scanContext->m_elements.end());

    EXPECT_EQ(scanContext->m_alerts.size(), 1);
    EXPECT_NE(scanContext->m_alerts.find(CVEID), scanContext->m_alerts.end());

    auto& alert = scanContext->m_alerts[CVEID];

    std::string alertScoreVersion {"cvss3"};

    EXPECT_STREQ(alert.at("vulnerability").at("cve").get_ref<const std::string&>().c_str(), CVEID.c_str());

    EXPECT_DOUBLE_EQ(
        alert.at("vulnerability").at("cvss").at(alertScoreVersion).at("base_score").get_ref<const double&>(),
        Utils::floatToDoubleRound(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scoreBase(), 2));

    EXPECT_STREQ(alert.at("vulnerability").at("enumeration").get_ref<const std::string&>().c_str(), "CVE");
    EXPECT_STREQ(alert.at("vulnerability").at("published").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->datePublished()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->reference()->c_str());
    EXPECT_STREQ(
        alert.at("vulnerability").at("severity").get_ref<const std::string&>().c_str(),
        Utils::toSentenceCase(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->severity()->str()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("status").get_ref<const std::string&>().c_str(), "Active");

    EXPECT_STREQ(alert.at("vulnerability").at("title").get_ref<const std::string&>().c_str(),
                 (CVEID + " affects " + scanContext->osName().data()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("type").get_ref<const std::string&>().c_str(), "Packages");
    EXPECT_STREQ(alert.at("vulnerability").at("updated").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->dateUpdated()->c_str());
}

TEST_F(ScanOsAlertDetailsBuilderTest, TestVulnerabilityCvss2)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "2",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, setOsData(_, _)).Times(1);
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    spRemediationDataCacheMock = std::make_shared<MockRemediationDataCache>();
    EXPECT_CALL(*spRemediationDataCacheMock, getRemediationData(_)).WillRepeatedly(testing::Return(Remediation {}));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_synchronization_SCHEMA));
    ASSERT_TRUE(parser.Parse(OS_SCAN_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorSynchronization::GetSyncMsg(reinterpret_cast<const char*>(buffer));
    auto scanContext =
        std::make_shared<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>(
            syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"INSERTED"})"_json;
    scanContext->m_isFirstScan = false;
    scanContext->m_matchConditions[CVEID] = {"version", MatchRuleCondition::DefaultStatus};

    TScanOsAlertDetailsBuilder<MockDatabaseFeedManager,
                               TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>
        scanOsAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(scanOsAlertDetailsAugmentation.handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);
    EXPECT_NE(scanContext->m_elements.find(CVEID), scanContext->m_elements.end());

    EXPECT_EQ(scanContext->m_alerts.size(), 1);
    EXPECT_NE(scanContext->m_alerts.find(CVEID), scanContext->m_alerts.end());

    auto& alert = scanContext->m_alerts[CVEID];

    std::string alertScoreVersion {"cvss2"};

    EXPECT_STREQ(alert.at("vulnerability").at("cve").get_ref<const std::string&>().c_str(), CVEID.c_str());

    EXPECT_DOUBLE_EQ(
        alert.at("vulnerability").at("cvss").at(alertScoreVersion).at("base_score").get_ref<const double&>(),
        Utils::floatToDoubleRound(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scoreBase(), 2));

    EXPECT_STREQ(alert.at("vulnerability").at("enumeration").get_ref<const std::string&>().c_str(), "CVE");
    EXPECT_STREQ(alert.at("vulnerability").at("published").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->datePublished()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->reference()->c_str());
    EXPECT_STREQ(
        alert.at("vulnerability").at("severity").get_ref<const std::string&>().c_str(),
        Utils::toSentenceCase(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->severity()->str()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("status").get_ref<const std::string&>().c_str(), "Active");

    EXPECT_STREQ(alert.at("vulnerability").at("title").get_ref<const std::string&>().c_str(),
                 (CVEID + " affects " + scanContext->osName().data()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("type").get_ref<const std::string&>().c_str(), "Packages");
    EXPECT_STREQ(alert.at("vulnerability").at("updated").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->dateUpdated()->c_str());
}

TEST_F(ScanOsAlertDetailsBuilderTest, TestSuccessfulScanOsAlertWasSolved)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, setOsData(_, _)).Times(1);
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    spRemediationDataCacheMock = std::make_shared<MockRemediationDataCache>();
    EXPECT_CALL(*spRemediationDataCacheMock, getRemediationData(_)).WillRepeatedly(testing::Return(Remediation {}));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_synchronization_SCHEMA));
    ASSERT_TRUE(parser.Parse(OS_SCAN_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorSynchronization::GetSyncMsg(reinterpret_cast<const char*>(buffer));
    auto scanContext =
        std::make_shared<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>(
            syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"DELETED"})"_json;
    scanContext->m_isFirstScan = false;
    scanContext->m_matchConditions[CVEID] = {"version", MatchRuleCondition::LessThan};

    TScanOsAlertDetailsBuilder<MockDatabaseFeedManager,
                               TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>
        scanOsAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(scanOsAlertDetailsAugmentation.handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);
    EXPECT_NE(scanContext->m_elements.find(CVEID), scanContext->m_elements.end());

    EXPECT_EQ(scanContext->m_alerts.size(), 1);
    EXPECT_NE(scanContext->m_alerts.find(CVEID), scanContext->m_alerts.end());

    auto& alert = scanContext->m_alerts[CVEID];

    std::string alertScoreVersion {"cvss3"};

    EXPECT_STREQ(alert.at("vulnerability").at("cve").get_ref<const std::string&>().c_str(), CVEID.c_str());

    EXPECT_DOUBLE_EQ(
        alert.at("vulnerability").at("cvss").at(alertScoreVersion).at("base_score").get_ref<const double&>(),
        Utils::floatToDoubleRound(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->scoreBase(), 2));

    EXPECT_STREQ(alert.at("vulnerability").at("enumeration").get_ref<const std::string&>().c_str(), "CVE");
    EXPECT_STREQ(alert.at("vulnerability").at("published").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->datePublished()->c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("reference").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->reference()->c_str());
    EXPECT_STREQ(
        alert.at("vulnerability").at("severity").get_ref<const std::string&>().c_str(),
        Utils::toSentenceCase(GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->severity()->str()).c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("status").get_ref<const std::string&>().c_str(), "Solved");

    EXPECT_STREQ(alert.at("vulnerability").at("title").get_ref<const std::string&>().c_str(),
                 (CVEID + " affecting " + scanContext->osName().data() + " was solved").c_str());
    EXPECT_STREQ(alert.at("vulnerability").at("type").get_ref<const std::string&>().c_str(), "Packages");
    EXPECT_STREQ(alert.at("vulnerability").at("updated").get_ref<const std::string&>().c_str(),
                 GetVulnerabilityDescription(fbBuilder.GetBufferPointer())->dateUpdated()->c_str());
}

TEST_F(ScanOsAlertDetailsBuilderTest, TestFirstScanNoAlerts)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, setOsData(_, _)).Times(1);
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    spRemediationDataCacheMock = std::make_shared<MockRemediationDataCache>();
    EXPECT_CALL(*spRemediationDataCacheMock, getRemediationData(_)).WillRepeatedly(testing::Return(Remediation {}));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_synchronization_SCHEMA));
    ASSERT_TRUE(parser.Parse(OS_SCAN_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorSynchronization::GetSyncMsg(reinterpret_cast<const char*>(buffer));
    auto scanContext =
        std::make_shared<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>(
            syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"DELETED"})"_json;
    scanContext->m_isFirstScan = true;
    scanContext->m_matchConditions[CVEID] = {"version", MatchRuleCondition::Equal};

    TScanOsAlertDetailsBuilder<MockDatabaseFeedManager,
                               TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>
        scanOsAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_NO_THROW(scanOsAlertDetailsAugmentation.handleRequest(scanContext));

    EXPECT_EQ(scanContext->m_elements.size(), 1);
    EXPECT_NE(scanContext->m_elements.find(CVEID), scanContext->m_elements.end());

    EXPECT_EQ(scanContext->m_alerts.size(), 0);
}

TEST_F(ScanOsAlertDetailsBuilderTest, TestUnknownOperation)
{
    flatbuffers::FlatBufferBuilder fbBuilder;
    auto vulnerabilityDescriptionData =
        NSVulnerabilityScanner::CreateVulnerabilityDescriptionDirect(fbBuilder,
                                                                     "accessComplexity_test_string",
                                                                     "assignerShortName_test_string",
                                                                     "attackVector_test_string",
                                                                     "authentication_test_string",
                                                                     "availabilityImpact_test_string",
                                                                     "classification_test_string",
                                                                     "confidentialityImpact_test_string",
                                                                     "cweId_test_string",
                                                                     "datePublished_test_string",
                                                                     "dateUpdated_test_string",
                                                                     "description_test_string",
                                                                     "integrityImpact_test_string",
                                                                     "privilegesRequired_test_string",
                                                                     "reference_test_string",
                                                                     "scope_test_string",
                                                                     8.3,
                                                                     "3",
                                                                     "severity_test_string",
                                                                     "userInteraction_test_string");
    fbBuilder.Finish(vulnerabilityDescriptionData);

    auto dbWrapper = std::make_unique<Utils::RocksDBWrapper>(TEST_DESCRIPTION_DATABASE_PATH);
    rocksdb::Slice dbValue(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());
    dbWrapper->put(CVEID, dbValue);

    auto mockGetVulnerabiltyDescriptiveInformation =
        [&](const std::string_view cveId,
            FlatbufferDataPair<NSVulnerabilityScanner::VulnerabilityDescription>& resultContainer)
    {
        dbWrapper->get(std::string(cveId), resultContainer.slice);
        resultContainer.data = const_cast<NSVulnerabilityScanner::VulnerabilityDescription*>(
            NSVulnerabilityScanner::GetVulnerabilityDescription(resultContainer.slice.data()));
    };

    Os osData {.hostName = "osdata_hostname",
               .architecture = "osdata_architecture",
               .name = "osdata_name",
               .codeName = "osdata_codeName",
               .majorVersion = "osdata_majorVersion",
               .minorVersion = "osdata_minorVersion",
               .patch = "osdata_patch",
               .build = "osdata_build",
               .platform = "osdata_platform",
               .version = "osdata_version",
               .release = "osdata_release",
               .displayVersion = "osdata_displayVersion",
               .sysName = "osdata_sysName",
               .kernelVersion = "osdata_kernelVersion",
               .kernelRelease = "osdata_kernelRelease"};

    spOsDataCacheMock = std::make_shared<MockOsDataCache>();
    EXPECT_CALL(*spOsDataCacheMock, setOsData(_, _)).Times(1);
    EXPECT_CALL(*spOsDataCacheMock, getOsData(_)).WillRepeatedly(testing::Return(osData));

    spRemediationDataCacheMock = std::make_shared<MockRemediationDataCache>();
    EXPECT_CALL(*spRemediationDataCacheMock, getRemediationData(_)).WillRepeatedly(testing::Return(Remediation {}));

    auto spDatabaseFeedManagerMock = std::make_shared<MockDatabaseFeedManager>();
    EXPECT_CALL(*spDatabaseFeedManagerMock, getVulnerabiltyDescriptiveInformation(_, _))
        .WillRepeatedly(testing::Invoke(mockGetVulnerabiltyDescriptiveInformation));

    flatbuffers::Parser parser;
    ASSERT_TRUE(parser.Parse(syscollector_synchronization_SCHEMA));
    ASSERT_TRUE(parser.Parse(OS_SCAN_MSG.c_str()));
    uint8_t* buffer = parser.builder_.GetBufferPointer();
    std::variant<const SyscollectorDeltas::Delta*, const SyscollectorSynchronization::SyncMsg*, const nlohmann::json*>
        syscollectorDelta = SyscollectorSynchronization::GetSyncMsg(reinterpret_cast<const char*>(buffer));
    auto scanContext =
        std::make_shared<TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>(
            syscollectorDelta);
    scanContext->m_elements[CVEID] = R"({"operation":"UNKNOWN"})"_json;
    scanContext->m_isFirstScan = false;

    TScanOsAlertDetailsBuilder<MockDatabaseFeedManager,
                               TScanContext<TrampolineOsDataCache, GlobalData, TrampolineRemediationDataCache>>
        scanOsAlertDetailsAugmentation(spDatabaseFeedManagerMock);

    EXPECT_THROW(scanOsAlertDetailsAugmentation.handleRequest(scanContext), std::runtime_error);

    EXPECT_EQ(scanContext->m_alerts.size(), 0);
}
